package com.gem.config;

import com.github.pagehelper.PageInterceptor;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.type.EnumOrdinalTypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author 刘聪
 * Created  on 2020/10/9
 */
@Configuration

@ComponentScan({"com.gem.service", "com.gem.advice"})
@EnableAspectJAutoProxy
@EnableTransactionManagement // 开启声明式事务
@PropertySource("classpath:db.properties")
@MapperScan("com.gem.mapper")
public class AppConfig {
    @Autowired
    Environment environment;

    /*数据源*/
    @Bean
    public DataSource dataSource() throws Exception {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(environment.getProperty("mysql_driver"));
        comboPooledDataSource.setJdbcUrl(environment.getProperty("mysql_url"));
        comboPooledDataSource.setUser(environment.getProperty("mysql_user"));
        comboPooledDataSource.setPassword(environment.getProperty("mysql_password"));
        return comboPooledDataSource;
    }


    /** mybait-spring */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.gem.entity");
        sqlSessionFactoryBean.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class);
        sqlSessionFactoryBean.setPlugins(new PageInterceptor());
        org.apache.ibatis.session.Configuration configuration =
                new org.apache.ibatis.session.Configuration();
        configuration.setLazyLoadingEnabled(true);
        configuration.setAggressiveLazyLoading(false);
        configuration.setCacheEnabled(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean;
    }

    /** 事务管理器配置 */
    @Bean
    public DataSourceTransactionManager transactionManager() throws Exception {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource());
        return dataSourceTransactionManager;
    }
}
